//
//  DebugMainSwitchCell.swift
//  YKSwiftDebugManager
//
//  Created by linghit on 2021/12/2.
//

import UIKit

class DebugMainSwitchCell: DebugBaseCollectionViewCell {
    
    private var switchCallBack:((Bool)->Bool)? = nil
    private var switchNBName:String = ""
    private lazy var titleLabel:UILabel = {
        let label = UILabel.init(frame: CGRect(x: 20, y: 10, width: self.frame.size.width * 0.4, height: 30))
        
        if #available(iOS 13.0, *) {
            label.textColor = .label
        } else {
            label.textColor = .black
        }
        label.font = UIFont.systemFont(ofSize: self.frame.size.width * 0.096, weight: .bold)
        label.textAlignment = .right
        return label
        
        
        //https://www.bilibili.com/video/av754137903/
    }()
    
    private lazy var mainSwitch:UISwitch = {
        let mainSwitch = UISwitch.init(frame: CGRect(x: self.titleLabel.frame.maxX + 5, y: 10, width: 0, height: 0))
        let scale = (self.frame.size.height/self.frame.size.width)*2
        mainSwitch.transform = CGAffineTransform.init(scaleX: scale, y: scale)
        return mainSwitch
    }()
    
    private lazy var mainButton:UIButton = {
        let mainButton = UIButton(type: .custom)
        mainButton.frame = self.mainSwitch.frame
        mainButton.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
        return mainButton
    }()
    
    @objc private func buttonClick(sender:UIButton)->Void
    {
        if self.switchCallBack != nil {
            var result = UserDefaults.standard.object(forKey: self.switchNBName) as? Bool ?? false
            result = self.switchCallBack!(!result);
            UserDefaults.standard.set(result, forKey: self.switchNBName)
            self.mainSwitch.setOn(result, animated: true)
        }
    }
    
    override func detail(indexPath: IndexPath) {
        super.detail(indexPath: indexPath)
        DebugManagerUtil.share.getSwitchDetail(indexPath: indexPath) { itemName, switchNBName, callBack in
            
            self.titleLabel.text = itemName
            self.switchNBName = switchNBName;
            self.switchCallBack = callBack;
            
            guard let result = UserDefaults.standard.object(forKey: self.switchNBName) as? Bool else {
                return
            }
            self.mainSwitch.setOn(result, animated: false)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()->Void{
        self.backgroundColor = .clear
        self.contentView.addSubview(self.titleLabel)
        self.contentView.addSubview(self.mainSwitch)
        self.contentView.addSubview(self.mainButton)
    }
    
}
